using Microsoft.AspNetCore.Mvc;
using Material.Mvc.Models;
using Material.Mvc.Services;
using System.Diagnostics;
using Microsoft.Extensions.Logging;

namespace OpenAi.Controllers
{
    public class ChatController : Controller
    {
        private readonly ICustomerService _customerService;
        private static readonly Dictionary<string, List<ChatMessageModel>> _chatHistories = new();
        private static readonly string _currentUserId = "user-1";
        private readonly ILogger<ChatController> _logger;

        /// <summary>
        /// 初始化ChatController
        /// </summary>
        /// <param name="customerService">智能客服服务</param>
        public ChatController(ICustomerService customerService, ILogger<ChatController> logger)
        {
            _customerService = customerService;
            _logger = logger;
        }

        /// <summary>
        /// 显示聊天页面
        /// </summary>
        /// <returns>聊天视图</returns>
        public IActionResult Index()
        {
            var viewModel = new ChatViewModel
            {
                ChatHistory = GetChatHistory()
            };
            return View(viewModel);
        }

        /// <summary>
        /// 发送消息到智能客服
        /// </summary>
        /// <param name="model">聊天视图模型</param>
        /// <returns>聊天视图</returns>
        [HttpPost]
        public async Task<IActionResult> SendMessage(ChatViewModel model)
        {
            if (!ModelState.IsValid || string.IsNullOrWhiteSpace(model.Message))
            {
                model.ChatHistory = GetChatHistory();
                return View("Index", model);
            }

            try
            {
                // 添加用户消息到历史记录
                var chatHistory = GetChatHistory();
                chatHistory.Add(new ChatMessageModel
                {
                    Role = "user",
                    Content = model.Message,
                    Timestamp = DateTime.Now
                });

                // 调用智能客服服务获取回复
                _logger.LogInformation("Calling CustomerService.ProcessMessageAsync for user: {UserId}", _currentUserId);
                model.Response = await _customerService.ProcessMessageAsync(_currentUserId, model.Message);
                _logger.LogInformation("Received response from CustomerService, length: {ResponseLength}", model.Response?.Length ?? 0);

                // 添加客服回复到历史记录
                if (!string.IsNullOrWhiteSpace(model.Response))
                {
                    chatHistory.Add(new ChatMessageModel
                    {
                        Role = "assistant",
                        Content = model.Response,
                        Timestamp = DateTime.Now
                    });
                }
                else
                {
                    _logger.LogWarning("Received empty response from CustomerService");
                    chatHistory.Add(new ChatMessageModel
                    {
                        Role = "assistant",
                        Content = "抱歉，我暂时无法提供回复，请稍后再试。",
                        Timestamp = DateTime.Now
                    });
                }

                // 限制历史记录长度
                if (chatHistory.Count > 20)
                {
                    chatHistory.RemoveRange(0, chatHistory.Count - 20);
                    _logger.LogInformation("Chat history trimmed to 20 messages");
                }

                // 更新视图模型
                model.ChatHistory = chatHistory;
                model.Message = string.Empty; // 清空输入框
            }
            catch (Exception ex)
            {
                // 记录详细错误信息
                _logger.LogError("Error sending message: {Message}", ex.Message);
                _logger.LogError("Stack trace: {StackTrace}", ex.StackTrace);
                
                // 添加错误消息到历史记录，确保用户能看到反馈
                var chatHistory = GetChatHistory();
                chatHistory.Add(new ChatMessageModel
                {
                    Role = "assistant",
                    Content = "抱歉，处理您的消息时发生错误，请稍后再试。",
                    Timestamp = DateTime.Now
                });
                
                // 提供更友好的错误信息
                if (ex.Message.Contains("OpenAI API"))
                {
                    ModelState.AddModelError(string.Empty, "与OpenAI服务通信失败，请稍后再试或检查API配置。");
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "发送消息失败，请稍后再试。");
                }
                
                model.ChatHistory = chatHistory;
            }

            return View("Index", model);
        }

        /// <summary>
        /// 清除聊天历史
        /// </summary>
        /// <returns>重定向到聊天页面</returns>
        [HttpPost]
        public async Task<IActionResult> ClearHistory()
        {
            try
            {
                await _customerService.ClearHistoryAsync(_currentUserId);
                _chatHistories.Remove(_currentUserId);
            }
            catch (Exception ex)
            {
                TempData["ErrorMessage"] = "清除历史记录失败: " + ex.Message;
            }

            return RedirectToAction("Index");
        }

        /// <summary>
        /// 获取或创建当前用户的聊天历史
        /// </summary>
        /// <returns>聊天历史列表</returns>
        private List<ChatMessageModel> GetChatHistory()
        {
            if (!_chatHistories.ContainsKey(_currentUserId))
            {
                _chatHistories[_currentUserId] = new List<ChatMessageModel>();
            }
            return _chatHistories[_currentUserId];
        }
    }
}